import os
import subprocess

def load_env_file(path):
    env_vars = {}
    if not os.path.exists(path):
        return env_vars
    with open(path, 'r') as f:
        for line in f:
            line = line.strip()
            if not line or line.startswith('#'):
                continue
            if '=' in line:
                key, val = line.split('=', 1)
                env_vars[key] = val
    return env_vars

def run_script(script_path, env_vars=None):
    env = os.environ.copy()
    if env_vars:
        env.update(env_vars)

    if not os.path.exists(script_path):
        return {"success": False, "output": f"脚本不存在: {script_path}"}

    try:
        result = subprocess.run(
            ["bash", script_path],
            capture_output=True,
            text=True,
            env=env
        )
        output = result.stdout.strip() or result.stderr.strip()
        return {"success": result.returncode == 0, "output": output}
    except Exception as e:
        return {"success": False, "output": str(e)}

def run_script_async(script_path, env_vars=None):
    """
    异步执行脚本（不阻塞等待）
    """
    env = os.environ.copy()
    if env_vars:
        env.update(env_vars)

    ll = os.path

    if not os.path.exists(script_path):
        return {"success": False, "output": f"脚本不存在: {script_path}"}

    try:
        # 异步执行脚本（不阻塞等待）
        subprocess.Popen(["bash", script_path], env=env)
        return {"success": True, "output": f"✅ 服务正在启动"}
    except Exception as e:
        return {"success": False, "output": str(e)}
